package com.bkgy.controller.allprocess.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bkgy.commom.model.QueryDTO;
import com.bkgy.controller.allprocess.dto.*;
import com.bkgy.controller.allprocess.entity.*;
import com.bkgy.controller.allprocess.mapper.AllProcessMapper;
import com.bkgy.controller.allprocess.mapper.Entity1630Mapper;
import com.bkgy.controller.allprocess.service.AllProcessService;
import com.bkgy.sys.common.entity.ResultData;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;


@Service

public class AllProcessServiceImpl extends ServiceImpl<Entity1630Mapper, TbYieldCal1630EntityExcel> implements AllProcessService {


    @Resource
    private HttpServletResponse response;

    @Autowired
    private AllProcessMapper allProcessMapper;

    /**
     * DB2时间格式
     */
    private static final DateTimeFormatter DB_DATE_TIME_FORMAT =
            DateTimeFormatter.ofPattern("yyyy-MM-dd-HH.mm.ss.SSSSSS");

    /**
     * 1630重卷单产线成材率表明细表_分页
     * @param request_get TbYieldRcl1630Entity
     * @return AllProcessIndexDetails
     * 变更：适配时间戳方式查询完成。
     */
    public ResultData getTbyieldRcl1630_page(TbYieldRcl1630Entity request_get) {
        //日期转换与赋值
        TbYieldRcl1630Entity request = setdatetime(request_get);

        try {
            Page<?> page = new Page<>(request.getPageIndex(), request.getPageSize());
            List<TbYieldRcl1630Entity> list = allProcessMapper.getTbyieldRcl1630_page(page,request);
            Integer count = allProcessMapper.getTbyieldRcl1630_pagecount(request);
            return ResultData.ResultDataSuccess(list, count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }
    }

    /**
     * 2150重卷单产线成材率表明细表_分页
     * @param request_get TbYieldRcl2150Entity
     * @return AllProcessIndexDetails
     * 变更：适配时间戳方式查询完成。
     */
    public ResultData getTbyieldRcl2150_page(TbYieldRcl2150Entity request_get) {
        //日期转换与赋值
        TbYieldRcl2150Entity request = setdatetime(request_get);
        try {
            Page<?> page = new Page<>(request.getPageIndex(), request.getPageSize());
            List<TbYieldRcl2150Entity> list = allProcessMapper.getTbyieldRcl2150_page(page,request);
            Integer count = allProcessMapper.getTbyieldRcl2150_pagecount(request);
            return ResultData.ResultDataSuccess(list, count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }
    }


    /**
     * 1870重卷单产线成材率表明细表_分页
     * @param request_get TbYieldRcl1870Entity
     * @return AllProcessIndexDetails
     * 变更：适配时间戳方式查询完成。
     */
    public ResultData getTbyieldRcl1870_page (TbYieldRcl1870Entity request_get) {
        //日期转换与赋值
        TbYieldRcl1870Entity request = setdatetime(request_get);
        try {
            Page<?> page = new Page<>(request.getPageIndex(), request.getPageSize());
            List<TbYieldRcl1870Entity> list = allProcessMapper.getTbyieldRcl1870_page(page,request);
            Integer count = allProcessMapper.getTbyieldRcl1870_pagecount(request);
            return ResultData.ResultDataSuccess(list, count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }
    }

    /**
     * 产品成材率全流程分析;
     * @param request_get TbAllpricessProductEntity
     * @return ResultData
     * 变更：适配时间戳方式查询完成。
     */
    public ResultData  getAllprocessProductRate (TbAllpricessProductEntity request_get) {
        //日期转换与赋值
        TbAllpricessProductEntity request = setdatetime(request_get);

        Page<?> page = new Page<>(request.getPageIndex(), request.getPageSize());

        //返回值
        AllprocessProductRate  allprocessProductRate = new AllprocessProductRate();

        //成材率
        List<TbAllpricessProductEntity> results = null;
        Integer count =0;

        //异常品规统计
        List<TbAllpricessProductEntity> catchllprocess  = null;
        Integer catchllprocess_count = 0;

        //返回给前端的总行数，取成材率总行数和异常品规统计总行数最小值
        int count_all=0;
        if(request.getLinename().equals("cal2150"))
        {
            results = allProcessMapper.getAllprocessProductRate2150(page,request);//产品成材率全流程分析
            count = allProcessMapper.getAllprocessProductRate2150_pagecount(request);

            catchllprocess = allProcessMapper.getcatchllprocess2150(page,request);//异常品规统计
            catchllprocess_count = allProcessMapper.getcatchllprocess2150_pagecount(request);
        }
        else if(request.getLinename().equals("cal1630"))
        {
            results = allProcessMapper.getAllprocessProductRate1630(page,request);//产品成材率全流程分析
            count = allProcessMapper.getAllprocessProductRate1630_pagecount(request);

            catchllprocess = allProcessMapper.getcatchllprocess1630(page,request);//异常品规统计
            catchllprocess_count = allProcessMapper.getcatchllprocess1630_pagecount(request);
        }
        else if(request.getLinename().equals("cgl1870"))
        {
            results = allProcessMapper.getAllprocessProductRate1870(page,request);//产品成材率全流程分析
            count = allProcessMapper.getAllprocessProductRate1870_pagecount(request);

            catchllprocess = allProcessMapper.getcatchllprocess1870(page,request);//异常品规统计
            catchllprocess_count = allProcessMapper.getcatchllprocess1870_pagecount(request);
        }
        else if(request.getLinename().equals("tcm2280"))
        {
            results = allProcessMapper.getAllprocessProductRate2280(page,request);//产品成材率全流程分析
            count = allProcessMapper.getAllprocessProductRate2280_pagecount(request);

            catchllprocess = allProcessMapper.getcatchllprocess2280(page,request);//异常品规统计
            catchllprocess_count = allProcessMapper.getcatchllprocess2280_pagecount(request);
        }
        allprocessProductRate.setAllprocess(results);
        allprocessProductRate.setCatchllprocess(catchllprocess);
        if(count>catchllprocess_count)
        {
            count_all=catchllprocess_count;
        }
        else {
            count_all=count;
        }

        //总成材率
//        List<TbAllpricessIndexEntity> results_totalYield = allProcessMapper.getTotalYield(dbegin,dend);
//        indexdetails.setTotalYield(results_totalYield);

        return ResultData.ResultDataSuccess(allprocessProductRate,count_all);
    }

    /**
     * 根据前台传入查询开始和查询结束日期，构造出三种时间格式以便后续表数据查询
     * @param request TbAllpricessIndexEntity
     * @return TbAllpricessIndexEntity
     */
    public TbAllpricessProductEntity setdatetime(TbAllpricessProductEntity request) {
        TbAllpricessProductEntity request_get = request;
        try {
            String[] array_startTime = request.getDbegin().split("-");//时间格式：2025-06-01 00:00:01
            String startTime = "";//时间格式：2025/6/01 00:00:01
            String dbegin_Times = "";//时间格式：20250703075254
            if (array_startTime.length > 0) {
                String month = array_startTime[1];
                if (!month.equals("10")) {
                    month = array_startTime[1].replace("0", "");
                }
                //构建时间格式：2025/6/01 00:00:01
                startTime = array_startTime[0] + "/" + month + "/" + array_startTime[2];

                //构建时间格式：20250703075254
                String times2 = array_startTime[2].replace(" ", "");
                times2 = times2.replace(":", "");
                dbegin_Times = array_startTime[0] + array_startTime[1] + times2;
            }
            request_get.setDbegin_rcl(startTime);//时间格式：2025/6/01 00:00:01
            request_get.setDbegin_Times(dbegin_Times);//时间格式：20250703075254
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String[] array_endTime = request.getDend().split("-");//时间格式：2025-06-01 00:00:01
            String endTime = "";//时间格式：2025/6/01 00:00:01
            String endTime_Times="";//时间格式：20250703075254
            if (array_endTime.length > 0) {
                String month = array_endTime[1];
                if(!month.equals("10"))
                {
                    month= array_endTime[1].replace("0","");
                }
                //构建时间格式：2025/6/01 00:00:01
                endTime = array_endTime[0] + "/" + month + "/" + array_endTime[2];

                //构建时间格式：20250703075254
                String times2=array_endTime[2].replace(" ","");
                times2 = times2.replace(":","");
                endTime_Times=array_endTime[0]+array_endTime[1]+times2;
            }
            request_get.setDend_rcl(endTime);
            request_get.setDend_Times(endTime_Times);//时间格式：20250703075254
        } catch (Exception e) {
            e.printStackTrace();
        }


        return request_get;
    }
    /**
     * 根据前台传入查询开始和查询结束日期，构造出三种时间格式以便后续表数据查询
     * @param request TbAllpricessIndexEntity
     * @return TbAllpricessIndexEntity
     */
    public TbYieldRcl1870Entity setdatetime(TbYieldRcl1870Entity request) {
        TbYieldRcl1870Entity request_get = request;
        try {
            String[] array_startTime = request.getDbegin().split("-");//时间格式：2025-06-01 00:00:01
            String startTime = "";//时间格式：2025/6/01 00:00:01
            String dbegin_Times = "";//时间格式：20250703075254
            if (array_startTime.length > 0) {
                String month = array_startTime[1];
                if (!month.equals("10")) {
                    month = array_startTime[1].replace("0", "");
                }
                //构建时间格式：2025/6/01 00:00:01
                startTime = array_startTime[0] + "/" + month + "/" + array_startTime[2];

                //构建时间格式：20250703075254
                String times2 = array_startTime[2].replace(" ", "");
                times2 = times2.replace(":", "");
                dbegin_Times = array_startTime[0] + array_startTime[1] + times2;
            }
            request_get.setDbegin_rcl(startTime);//时间格式：2025/6/01 00:00:01
            request_get.setDbegin_Times(dbegin_Times);//时间格式：20250703075254
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String[] array_endTime = request.getDend().split("-");//时间格式：2025-06-01 00:00:01
            String endTime = "";//时间格式：2025/6/01 00:00:01
            String endTime_Times="";//时间格式：20250703075254
            if (array_endTime.length > 0) {
                String month = array_endTime[1];
                if(!month.equals("10"))
                {
                    month= array_endTime[1].replace("0","");
                }
                //构建时间格式：2025/6/01 00:00:01
                endTime = array_endTime[0] + "/" + month + "/" + array_endTime[2];

                //构建时间格式：20250703075254
                String times2=array_endTime[2].replace(" ","");
                times2 = times2.replace(":","");
                endTime_Times=array_endTime[0]+array_endTime[1]+times2;
            }
            request_get.setDend_rcl(endTime);
            request_get.setDend_Times(endTime_Times);//时间格式：20250703075254
        } catch (Exception e) {
            e.printStackTrace();
        }


        return request_get;
    }

    /**
     * 根据前台传入查询开始和查询结束日期，构造出三种时间格式以便后续表数据查询
     * @param request TbAllpricessIndexEntity
     * @return TbAllpricessIndexEntity
     */
    public TbYieldRcl2150Entity setdatetime(TbYieldRcl2150Entity request) {
        TbYieldRcl2150Entity request_get = request;
        try {
            String[] array_startTime = request.getDbegin().split("-");//时间格式：2025-06-01 00:00:01
            String startTime = "";//时间格式：2025/6/01 00:00:01
            String dbegin_Times = "";//时间格式：20250703075254
            if (array_startTime.length > 0) {
                String month = array_startTime[1];
                if (!month.equals("10")) {
                    month = array_startTime[1].replace("0", "");
                }
                //构建时间格式：2025/6/01 00:00:01
                startTime = array_startTime[0] + "/" + month + "/" + array_startTime[2];

                //构建时间格式：20250703075254
                String times2 = array_startTime[2].replace(" ", "");
                times2 = times2.replace(":", "");
                dbegin_Times = array_startTime[0] + array_startTime[1] + times2;
            }
            request_get.setDbegin_rcl(startTime);//时间格式：2025/6/01 00:00:01
            request_get.setDbegin_Times(dbegin_Times);//时间格式：20250703075254
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String[] array_endTime = request.getDend().split("-");//时间格式：2025-06-01 00:00:01
            String endTime = "";//时间格式：2025/6/01 00:00:01
            String endTime_Times="";//时间格式：20250703075254
            if (array_endTime.length > 0) {
                String month = array_endTime[1];
                if(!month.equals("10"))
                {
                    month= array_endTime[1].replace("0","");
                }
                //构建时间格式：2025/6/01 00:00:01
                endTime = array_endTime[0] + "/" + month + "/" + array_endTime[2];

                //构建时间格式：20250703075254
                String times2=array_endTime[2].replace(" ","");
                times2 = times2.replace(":","");
                endTime_Times=array_endTime[0]+array_endTime[1]+times2;
            }
            request_get.setDend_rcl(endTime);
            request_get.setDend_Times(endTime_Times);//时间格式：20250703075254
        } catch (Exception e) {
            e.printStackTrace();
        }


        return request_get;
    }


    /**
     * 根据前台传入查询开始和查询结束日期，构造出三种时间格式以便后续表数据查询
     * @param request TbAllpricessIndexEntity
     * @return TbAllpricessIndexEntity
     */
    public TbYieldRcl1630Entity setdatetime(TbYieldRcl1630Entity request) {
        TbYieldRcl1630Entity request_get = request;
        try {
            String[] array_startTime = request.getDbegin().split("-");//时间格式：2025-06-01 00:00:01
            String startTime = "";//时间格式：2025/6/01 00:00:01
            String dbegin_Times = "";//时间格式：20250703075254
            if (array_startTime.length > 0) {
                String month = array_startTime[1];
                if (!month.equals("10")) {
                    month = array_startTime[1].replace("0", "");
                }
                //构建时间格式：2025/6/01 00:00:01
                startTime = array_startTime[0] + "/" + month + "/" + array_startTime[2];

                //构建时间格式：20250703075254
                String times2 = array_startTime[2].replace(" ", "");
                times2 = times2.replace(":", "");
                dbegin_Times = array_startTime[0] + array_startTime[1] + times2;
            }
            request_get.setDbegin_rcl(startTime);//时间格式：2025/6/01 00:00:01
            request_get.setDbegin_Times(dbegin_Times);//时间格式：20250703075254
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String[] array_endTime = request.getDend().split("-");//时间格式：2025-06-01 00:00:01
            String endTime = "";//时间格式：2025/6/01 00:00:01
            String endTime_Times="";//时间格式：20250703075254
            if (array_endTime.length > 0) {
                String month = array_endTime[1];
                if(!month.equals("10"))
                {
                    month= array_endTime[1].replace("0","");
                }
                //构建时间格式：2025/6/01 00:00:01
                endTime = array_endTime[0] + "/" + month + "/" + array_endTime[2];

                //构建时间格式：20250703075254
                String times2=array_endTime[2].replace(" ","");
                times2 = times2.replace(":","");
                endTime_Times=array_endTime[0]+array_endTime[1]+times2;
            }
            request_get.setDend_rcl(endTime);
            request_get.setDend_Times(endTime_Times);//时间格式：20250703075254
        } catch (Exception e) {
            e.printStackTrace();
        }


        return request_get;
    }

    /**
     * 根据前台传入查询开始和查询结束日期，构造出三种时间格式以便后续表数据查询
     * @param request TbAllpricessIndexEntity
     * @return TbAllpricessIndexEntity
     */
    public TbAllpricessIndexEntity setdatetime(TbAllpricessIndexEntity request) {
        TbAllpricessIndexEntity request_get = request;
        try {
            String[] array_startTime = request.getDbegin().split("-");//时间格式：2025-06-01 00:00:01
            String startTime = "";//时间格式：2025/6/01 00:00:01
            String dbegin_Times = "";//时间格式：20250703075254
            if (array_startTime.length > 0) {
                String month = array_startTime[1];
                if (!month.equals("10")) {
                    month = array_startTime[1].replace("0", "");
                }
                //构建时间格式：2025/6/01 00:00:01
                startTime = array_startTime[0] + "/" + month + "/" + array_startTime[2];

                //构建时间格式：20250703075254
                String times2 = array_startTime[2].replace(" ", "");
                times2 = times2.replace(":", "");
                dbegin_Times = array_startTime[0] + array_startTime[1] + times2;
            }
            request_get.setDbegin_Rcl(startTime);//时间格式：2025/6/01 00:00:01
            request_get.setDbegin_Times(dbegin_Times);//时间格式：20250703075254
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String[] array_endTime = request.getDend().split("-");//时间格式：2025-06-01 00:00:01
            String endTime = "";//时间格式：2025/6/01 00:00:01
            String endTime_Times="";//时间格式：20250703075254
            if (array_endTime.length > 0) {
                String month = array_endTime[1];
                if(!month.equals("10"))
                {
                    month= array_endTime[1].replace("0","");
                }
                //构建时间格式：2025/6/01 00:00:01
                endTime = array_endTime[0] + "/" + month + "/" + array_endTime[2];

                //构建时间格式：20250703075254
                String times2=array_endTime[2].replace(" ","");
                times2 = times2.replace(":","");
                endTime_Times=array_endTime[0]+array_endTime[1]+times2;
            }
            request_get.setDend_Rcl(endTime);
            request_get.setDend_Times(endTime_Times);//时间格式：20250703075254
        } catch (Exception e) {
            e.printStackTrace();
        }


        return request_get;
    }

    /**
     * 全流程成材率模型首页数据;
     * @param request_get TbAllpricessIndexEntity
     * @return AllProcessIndexDetails
     * 变更：适配时间戳方式查询完成。
     */
    public  ResultData<AllProcessIndexDetails> getAllprocessIndexDetails (TbAllpricessIndexEntity request_get) {
        //日期转换与赋值
        TbAllpricessIndexEntity request = setdatetime(request_get);
        try {
            Page<?> page = new Page<>(request.getPageIndex(), request.getPageSize());

            //总行数数
            int count = 0;

            // 构建响应对象
            AllProcessIndexDetails indexdetails = new AllProcessIndexDetails();

            //机组计算成材率
            List<TbAllpricessIndexEntity> results = new ArrayList<>();
            if(request_get.getLinename()==null)
            {
                request_get.setLinename("cal1630");
            }
            if(request.getLinename().equals("all"))
            {
                results = allProcessMapper.gettAllProcessIndexDetails(page, request);
            }
            else if(request.getLinename().equals("cal1630"))
            {
                results = allProcessMapper.gettAllProcessIndexDetails1630(page, request);
            }
            else if(request.getLinename().equals("cal2150"))
            {
                results = allProcessMapper.gettAllProcessIndexDetails2150(page, request);
            }
            else if(request.getLinename().equals("cgl1870"))
            {
                results = allProcessMapper.gettAllProcessIndexDetails1870(page, request);
            }
            else if(request.getLinename().equals("tcm2280"))
            {
                results = allProcessMapper.gettAllProcessIndexDetails2280(page, request);
            }
            else if(request.getLinename().equals("rcl1630"))
            {
                results = allProcessMapper.gettAllProcessIndexDetailsRcl1630(page, request);
            }
            else if(request.getLinename().equals("rcl2150"))
            {
                results = allProcessMapper.gettAllProcessIndexDetailsRcl2150(page, request);
            }
            else if(request.getLinename().equals("rcl1870"))
            {
                results = allProcessMapper.gettAllProcessIndexDetailsRcl1870(page, request);
            }
//            List<TbAllpricessIndexEntity> results = allProcessMapper.gettAllProcessIndexDetails(page, request);
            indexdetails.setUnitCalculationYield(results);

            //总成材率=冷轧成材率 + 镀锌成材率
            //全流程成材率模型首页数据-冷轧成材率（酸轧到两个连退线的成材率）
            List<TbAllpricessIndexEntity> results_totalYield = new ArrayList();

            //2025年7月1日本溪三冷侯亮对该功能进行变更，由总的冷轧成才率，拆为1630和2150连退成材率，故该功能废弃
//            List<TbAllpricessIndexEntity> results_totalYield_cal = allProcessMapper.getTotalYield_cal(page, request);
//            if (!results_totalYield_cal.isEmpty()) {
//                results_totalYield.add(results_totalYield_cal.get(0));
//            }

            //全流程成材率模型首页数据-冷轧成材率（酸轧到1630连退线的成材率）
            List<TbAllpricessIndexEntity> results_totalYield_cal1630 = allProcessMapper.getTotalYield_cal1630(page, request);
            if (!results_totalYield_cal1630.isEmpty()) {
                results_totalYield.add(results_totalYield_cal1630.get(0));
            }

            //全流程成材率模型首页数据-冷轧成材率（酸轧到2150连退线的成材率）
            List<TbAllpricessIndexEntity> results_totalYield_cal2150 = allProcessMapper.getTotalYield_cal2150(page, request);
            if (!results_totalYield_cal2150.isEmpty()) {
                results_totalYield.add(results_totalYield_cal2150.get(0));
            }

            /*三冷冷轧总成材率=酸轧-两个连退线*/
            TbAllpricessIndexEntity entity_CalYield = new TbAllpricessIndexEntity();
            BigDecimal Calznyield = new BigDecimal(0);//三冷冷轧 总成材率
            BigDecimal Calex_wt = new BigDecimal(0);//三冷冷轧 出口重量
            BigDecimal Calen_wt = new BigDecimal(0);//三冷冷轧 入口重量
            if (!results_totalYield_cal1630.isEmpty()) {
                Calex_wt = Calex_wt.add(results_totalYield_cal1630.get(0).getExwt());//出口重量
                Calen_wt = Calen_wt.add(results_totalYield_cal1630.get(0).getEnwt());//入口重量
            }

            if (!results_totalYield_cal2150.isEmpty()) {
                Calex_wt = Calex_wt.add(results_totalYield_cal2150.get(0).getExwt());//出口重量
                Calen_wt = Calen_wt.add(results_totalYield_cal2150.get(0).getEnwt());//入口重量
            }
            if (Calen_wt.compareTo(new BigDecimal("0")) != 0) {
                Calznyield = Calex_wt.divide(Calen_wt, 3, BigDecimal.ROUND_HALF_UP);
            }

            Calznyield = Calznyield.multiply(new BigDecimal(100));
            entity_CalYield.setLinename("cal");
            entity_CalYield.setTotalznyield(Calznyield);
            entity_CalYield.setTargetvalue(Convert.toBigDecimal(0.9444).multiply(new BigDecimal(100)));
            results_totalYield.add(entity_CalYield);
            indexdetails.setTotalYield(results_totalYield);

            //全流程成材率模型首页数据-镀锌成材率（酸轧到镀锌线成材率）
            List<TbAllpricessIndexEntity> results_totalYield_cgl = allProcessMapper.getTotalYield_cgl(page, request);
            if (!results_totalYield_cgl.isEmpty()) {
                results_totalYield.add(results_totalYield_cgl.get(0));
            }

            //遍历计算总成材率
            TbAllpricessIndexEntity entity_totalYield = new TbAllpricessIndexEntity();
            BigDecimal totalznyield = new BigDecimal(0);//总成材率
            BigDecimal ex_wt = new BigDecimal(0);//出口重量
            BigDecimal en_wt = new BigDecimal(0);//入口重量
            if (!results_totalYield_cal1630.isEmpty()) {
                ex_wt = ex_wt.add(results_totalYield_cal1630.get(0).getExwt());//出口重量
                en_wt = en_wt.add(results_totalYield_cal1630.get(0).getEnwt());//入口重量
            }
            if (!results_totalYield_cal2150.isEmpty()) {
                ex_wt = ex_wt.add(results_totalYield_cal2150.get(0).getExwt());//出口重量
                en_wt = en_wt.add(results_totalYield_cal2150.get(0).getEnwt());//入口重量
            }
            if (!results_totalYield_cgl.isEmpty()) {
                ex_wt = ex_wt.add(results_totalYield_cgl.get(0).getExwt());//出口重量
                en_wt = en_wt.add(results_totalYield_cgl.get(0).getEnwt());//入口重量
            }
            if (en_wt.compareTo(new BigDecimal("0")) != 0) {
                totalznyield = ex_wt.divide(en_wt, 3, BigDecimal.ROUND_HALF_UP);
            }

            totalznyield = totalznyield.multiply(new BigDecimal(100));
            entity_totalYield.setLinename("all");
            entity_totalYield.setTotalznyield(totalznyield);
            entity_totalYield.setTargetvalue(Convert.toBigDecimal(0.9415).multiply(new BigDecimal(100)));
            results_totalYield.add(entity_totalYield);
            indexdetails.setTotalYield(results_totalYield);


            //产品品类
            List<TbAllpricessIndexEntity> results_productType = new ArrayList<>();
            if(request.getLinename()==null)
            {
                request.setLinename("cal1630");
            }
            if(request.getLinename().equals("all"))
            {
                results_productType = allProcessMapper.getproductTypeAll(page, request);
            }
            else if(request.getLinename().equals("cal1630"))
            {
                results_productType = allProcessMapper.getproductTypeCal1630(page, request);
            }
            else if(request.getLinename().equals("cal2150"))
            {
                results_productType = allProcessMapper.getproductTypeCal2150(page, request);
            }
            else if(request.getLinename().equals("cgl1870"))
            {
                results_productType = allProcessMapper.getproductTypeCgl1870(page, request);
            }
            else if(request.getLinename().equals("tcm2280"))
            {
                results_productType = allProcessMapper.getproductTypeTcm2280(page, request);
            }
            else if(request.getLinename().equals("rcl1630"))
            {
                results_productType = allProcessMapper.getproductTypeRcl1630(page, request);
            }
            else if(request.getLinename().equals("rcl2150"))
            {
                results_productType = allProcessMapper.getproductTypeRcl2150(page, request);
            }
            else if(request.getLinename().equals("rcl1870"))
            {
                results_productType = allProcessMapper.getproductTypeRcl1870(page, request);
            }

            if (!results_productType.isEmpty()) {
                count = results_productType.size();//总行数数
            }
            indexdetails.setProductType(results_productType);

            //其它具体原因
//            List<TbAllpricessIndexEntity> results_otherReason = allProcessMapper.getotherReason(page, request);
            List<TbAllpricessIndexEntity> results_otherReason = new ArrayList<>();
            if(request.getLinename()==null)
            {
                request.setLinename("cal1630");
            }
            if(request.getLinename().equals("all"))
            {
                results_otherReason= allProcessMapper.getotherReasonAll(page, request);
            }
            else if(request.getLinename().equals("cal1630"))
            {
                results_otherReason= allProcessMapper.getotherReason1630(page, request);
            }
            else if(request.getLinename().equals("cal2150"))
            {
                results_otherReason= allProcessMapper.getotherReason2150(page, request);
            }
            else if(request.getLinename().equals("cgl1870"))
            {
                results_otherReason= allProcessMapper.getotherReason1870(page, request);
            }
            else if(request.getLinename().equals("tcm2280"))
            {
                results_otherReason= allProcessMapper.getotherReason2280(page, request);
            }
            if (!results_otherReason.isEmpty()) {
                int count_otherReason = results_otherReason.size();//总行数数
                if (count_otherReason < count) {
                    count = count_otherReason;//将最小的count给前端
                }
            }
            indexdetails.setOtherReason(results_otherReason);

            //未完成原因
//          List<TbAllpricessIndexEntity> results_unCompleteReason = allProcessMapper.getunCompleteReason(page,request);
            List<TbAllpricessIndexEntity> results_unCompleteReason = new ArrayList<>();
            TbAllpricessIndexEntity entity = new TbAllpricessIndexEntity();
            String unCompleteReason_str = "";
            if (!results_otherReason.isEmpty()) {
                if (results_otherReason.size() >= 4) {
                    for (int i = 0; i < 4; i++) {
                        unCompleteReason_str += results_otherReason.get(i).getUncompletereason().toString() + "。";
                    }
                } else {
                    for (int i = 0; i < results_otherReason.size(); i++) {
                        unCompleteReason_str += results_otherReason.get(i).getUncompletereason().toString() + "。";
                    }
                }
                entity.setUncompletereason(unCompleteReason_str);
                results_unCompleteReason.add(entity);
            }

            indexdetails.setUnCompleteReason(results_unCompleteReason);

            return ResultData.ResultDataSuccess(indexdetails, count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }
    }

    /**
     * 2280酸轧线成材率表明细表_分页;
     * @param tbYieldTcm2280Entity_request 实体表
     * @return ResultData
     */
    public ResultData getTbyieldtcm2280_page(TbYieldTcm2280Entity tbYieldTcm2280Entity_request)
    {
        try {
            Integer count =0;
            Page<?> page = new Page<>(tbYieldTcm2280Entity_request.getPageIndex(), tbYieldTcm2280Entity_request.getPageSize());
            tbYieldTcm2280Entity_request.setDbegin(tbYieldTcm2280Entity_request.getDbegin().substring(0,10));
            tbYieldTcm2280Entity_request.setDend(tbYieldTcm2280Entity_request.getDend().substring(0,10));
            List<TbYieldTcm2280Entity> list = allProcessMapper.getTbyieldtcm2280Details_page(page,tbYieldTcm2280Entity_request);
            count = (int)page.getTotal();
            return ResultData.ResultDataSuccess(list, count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }
    }

    /**
     * getTbyieldtcm2280，得到2280酸轧线成材率表明细表;
     * @param hotCoilId 入口钢卷号
     * @param coldCoilId 出口卷号
     * @param dbegin 开始时间
     * @param dend 结束时间
     * @return AllProcessTbyieldtcm2280Details
     */
    public ResultData<AllProcessTbyieldtcm2280Details> getTbyieldtcm2280(String hotCoilId, String coldCoilId, String dbegin, String dend) {

        List<TbYieldTcm2280Entity> results = allProcessMapper.getTbyieldtcm2280Details(hotCoilId,coldCoilId,dbegin,dend);
        // 构建响应对象
        AllProcessTbyieldtcm2280Details detais_2280 = new AllProcessTbyieldtcm2280Details();
        detais_2280.setTbyieldtcm2280Details(results);

        return ResultData.ResultDataSuccess(detais_2280);
    }

    /**
     * 得到2150连退线成材率表明细表;
     * @param coldCoilId 入口钢卷号
     * @param calCoilId 出口卷号
     * @param dbegin 开始时间
     * @param dend 结束时间
     */
    public ResultData<AllProcessTbyieldcal2150Details> getTbyieldcal2150(String coldCoilId, String calCoilId, String dbegin, String dend) {
        List<TbYieldCal2150Entity> results = allProcessMapper.getTbyieldcal2150Details(coldCoilId,calCoilId,dbegin,dend);
        // 构建响应对象
        AllProcessTbyieldcal2150Details detais_2150 = new AllProcessTbyieldcal2150Details();
        detais_2150.setTbyieldcal2150Details(results);
        return ResultData.ResultDataSuccess(detais_2150);
    }

    /**
     * 2150连退线成材率表明细表_分页;
     * @param request TbYieldCal2150Entity实体表
     * @return ResultData
     */
    public ResultData getTbyieldcal2150_page(TbYieldCal2150Entity request){
        try {
            Integer count =0;
            Page<?> page = new Page<>(request.getPageIndex(), request.getPageSize());
            request.setDbegin(request.getDbegin().substring(0,10));
            request.setDend(request.getDend().substring(0,10));
            List<TbYieldCal2150Entity> list = allProcessMapper.getTbyieldcal2150Details_page(page,request);
            count = (int)page.getTotal();
            return ResultData.ResultDataSuccess(list, count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }
    }


    /**
     * getTbyieldcal1630Detais，得到1630线成材率明细表;
     * @param coldCoilId 入口钢卷号
     * @param calCoilId 出口卷号
     * @param dbegin 开始时间
     * @param dend 结束时间
     * @return AllProcessTbyieldcal1630Details
     */
    public ResultData<AllProcessTbyieldcal1630Details> getTbyieldcal1630(String coldCoilId, String calCoilId, String dbegin, String dend) {
        try {
            List<TbYieldCal1630Entity> results = allProcessMapper.getTbyieldcal1630Details(coldCoilId, calCoilId, dbegin, dend);
            // 构建响应对象
            AllProcessTbyieldcal1630Details detais_1630 = new AllProcessTbyieldcal1630Details();
            detais_1630.setTbyieldcal1630Details(results);

            return ResultData.ResultDataSuccess(detais_1630);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }
    }

    /**
     * 1630连退线成材率表明细表_分页;
     * @param request TbYieldCal1630Entity实体表
     * @return ResultData
     */
    public ResultData getTbyieldcal1630_page(TbYieldCal1630Entity request){
        try {
            Integer count=0;
            Page<?> page = new Page<>(request.getPageIndex(), request.getPageSize());
            request.setDbegin(request.getDbegin().substring(0,10));
            request.setDend(request.getDend().substring(0,10));
            List<TbYieldCal1630Entity> list = allProcessMapper.getTbyieldcal1630Details_page(page,request);
            count = (int)page.getTotal();
            return ResultData.ResultDataSuccess(list, count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }
    }

    /**
     * 重卷1630连退线成材率表明细表_分页;
     * @param request TbYieldCal1630Entity实体表
     * @return ResultData
     */
    public ResultData getTbyieldRcl1630_page(TbYieldCal1630Entity request){
        try {
            Integer count =0;
            Page<?> page = new Page<>(request.getPageIndex(), request.getPageSize());
            List<TbYieldCal1630Entity> list = allProcessMapper.getTbyieldcal1630Details_page(page,request);
            count = (int)page.getTotal();
//            Integer count = allProcessMapper.getTbyieldcal1630Details_pagecount(request);
//            if(!list.isEmpty()){
//                count=list.size();
//            }
            return ResultData.ResultDataSuccess(list, count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }
    }

    /**
     * getTbyieldtcmDetais，得到1870镀锌线成材率明细表;
     * @param coldCoilId 入口钢卷号
     * @param cglCoilId 出口卷号
     * @param dbegin 开始时间
     * @param dend 结束时间
     * @return AllProcessTbyieldtcmDetais
     */
    public ResultData<AllProcessTbyieldtcmDetais> getTbyieldtcmDetais(String coldCoilId,String cglCoilId,String dbegin,String dend) {
        List<TbYieldCglEntity> results = allProcessMapper.getTbyieldtcmDetais(coldCoilId,cglCoilId,dbegin,dend);
        // 构建响应对象
        AllProcessTbyieldtcmDetais detais = new AllProcessTbyieldtcmDetais();
        detais.setTbyieldtcmDetais(results);
        return ResultData.ResultDataSuccess(detais);
    }

    /**
     * 1870镀锌线成材率明细表_分页;
     * @param request TbYieldCglEntity实体表
     * @return ResultData
     */
    public ResultData getTbyieldtcmDetais_page(TbYieldCglEntity request) {
        try {
            Integer count=0;
            Page<?> page = new Page<>(request.getPageIndex(), request.getPageSize());
            request.setDbegin(request.getDbegin().substring(0,10));
            request.setDend(request.getDend().substring(0,10));
            List<TbYieldCglEntity> list = allProcessMapper.getTbyieldtcmDetais_page(page,request);
            count = (int)page.getTotal();
            return ResultData.ResultDataSuccess(list, count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("获取失败" + e.getMessage(), null);
        }
    }

    @Override
    public ResultData<AllProcessSerchDto> getputhead_month(String timeType, LocalDate date) {
        // 计算时间范围
        LocalDateTime startTime = getStartTime(timeType, date);
        LocalDateTime endTime = getEndTime(timeType, date);
        String stime = startTime.format(DB_DATE_TIME_FORMAT);//转为数据库格式，方便数据查询
        String etime = endTime.format(DB_DATE_TIME_FORMAT);

        LocalDateTime now = LocalDateTime.now(); // 获取当前时间
        YearMonth currentYearMonth = YearMonth.from(now); // 获取当前年月  //2025-05
        YearMonth lastMonthYearMonth = currentYearMonth.minusMonths(1); // 上个月  2025-04


        // 查询
        List<TbYieldTcmEntity> results = allProcessMapper.getputhead_month(stime, etime);

        // 构建响应对象
        AllProcessSerchDto response = new AllProcessSerchDto();
        response.setCutheadList(results);
        response.setSteel_grade(results);

        return ResultData.ResultDataSuccess(response);
    }


    /**
     * 根据时间类型计算开始时间
     */
    private LocalDateTime getStartTime(String timeType, LocalDate date) {
        if ("day".equals(timeType)) {
            return LocalDateTime.of(date, LocalTime.MIN);
        } else if ("week".equals(timeType)) {
            return LocalDateTime.of(date.with(DayOfWeek.MONDAY), LocalTime.MIN);
        } else if ("month".equals(timeType)) {
            return LocalDateTime.of(date.withDayOfMonth(1), LocalTime.MIN);
        }
        throw new IllegalArgumentException("不支持的时间类型：" + timeType);
    }

    /**
     * 根据时间类型计算结束时间
     */
    private LocalDateTime getEndTime(String timeType, LocalDate date) {
        if ("day".equals(timeType)) {
            return LocalDateTime.of(date, LocalTime.MAX);
        } else if ("week".equals(timeType)) {
            return LocalDateTime.of(date.with(DayOfWeek.SUNDAY), LocalTime.MAX);
        } else if ("month".equals(timeType)) {
            return LocalDateTime.of(date.withDayOfMonth(date.lengthOfMonth()), LocalTime.MAX);
        }
        throw new IllegalArgumentException("不支持的时间类型：" + timeType);
    }



        /**
         * 1630产线成材率异常原因客户输入
         * @param request TbYieldCal1630Entity
         */
    public ResultData updateAbnormalReason1630(TbYieldCal1630Entity request) {
        try {
            Integer row = allProcessMapper.updateAbnormalReason1630(request);
            return ResultData.ResultDataSuccessSelf("修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("修改失败,失败信息为" + e.getMessage(), null);
        }
    }

    /**
     * 2150产线成材率异常原因客户输入
     * @param request TbYieldCal2150Entity
     */
    public ResultData updateAbnormalReason2150(TbYieldCal2150Entity request){
        try {
            Integer row = allProcessMapper.updateAbnormalReason2150(request);
            return ResultData.ResultDataSuccessSelf("修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("修改失败,失败信息为" + e.getMessage(), null);
        }
    }
    /**
     * 1870产线成材率异常原因客户输入
     * @param request TbYieldCglEntity
     */
    public ResultData updateAbnormalReason1870(TbYieldCglEntity request){
        try {
            Integer row = allProcessMapper.updateAbnormalReason1870(request);
            return ResultData.ResultDataSuccessSelf("修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("修改失败,失败信息为" + e.getMessage(), null);
        }
    }
    /**
     * 2280产线成材率异常原因客户输入
     * @param request TbYieldTcm2280Entity
     */
    public ResultData updateAbnormalReason2280(TbYieldTcm2280Entity request)
    {
        try {
            Integer row = allProcessMapper.updateAbnormalReason2280(request);
            return ResultData.ResultDataSuccessSelf("修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("修改失败,失败信息为" + e.getMessage(), null);
        }
    }

    /**
     * 1630产线成材率异常原因客户输入_批量
     * @param json JSONObject
     */
    public  ResultData updateAbnormalReason1630_List(JSONObject json)
    {
        try {
            String abnormalReason = json.getString("abnormalReason");
            JSONArray jsonArray_coilds = json.getJSONArray("coilds");
            List<String> coilds = jsonArray_coilds.toJavaList(String.class);
            if (CollectionUtils.isEmpty(coilds)) {
                return ResultData.ResultDataFaultSelf(null, "出口卷号不能为空");
            }

            allProcessMapper.updateAbnormalReason1630_List(coilds,abnormalReason);
            return ResultData.ResultDataSuccessSelf("修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("修改失败,失败信息为" + e.getMessage(), null);
        }
    }


    /**
     * 2150产线成材率异常原因客户输入_批量
     * @param json JSONObject
     */
    public  ResultData updateAbnormalReason2150_List(JSONObject json)
    {
        try {
            String abnormalReason = json.getString("abnormalReason");
            JSONArray jsonArray_coilds = json.getJSONArray("coilds");
            List<String> coilds = jsonArray_coilds.toJavaList(String.class);
            if (CollectionUtils.isEmpty(coilds)) {
                return ResultData.ResultDataFaultSelf(null, "出口卷号不能为空");
            }

            allProcessMapper.updateAbnormalReason2150_List(coilds,abnormalReason);
            return ResultData.ResultDataSuccessSelf("修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("修改失败,失败信息为" + e.getMessage(), null);
        }
    }

    /**
     * 1870产线成材率异常原因客户输入_批量
     * @param json JSONObject
     */
    public  ResultData updateAbnormalReason1870_List(JSONObject json)
    {
        try {
            String abnormalReason = json.getString("abnormalReason");
            JSONArray jsonArray_coilds = json.getJSONArray("coilds");
            List<String> coilds = jsonArray_coilds.toJavaList(String.class);
            if (CollectionUtils.isEmpty(coilds)) {
                return ResultData.ResultDataFaultSelf(null, "出口卷号不能为空");
            }

            allProcessMapper.updateAbnormalReason1870_List(coilds,abnormalReason);
            return ResultData.ResultDataSuccessSelf("修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("修改失败,失败信息为" + e.getMessage(), null);
        }
    }


    /**
     * 2280产线成材率异常原因客户输入_批量
     * @param json JSONObject
     */
    public  ResultData updateAbnormalReason2280_List(JSONObject json)
    {
        try {
            String abnormalReason = json.getString("abnormalReason");
            JSONArray jsonArray_coilds = json.getJSONArray("coilds");
            List<String> coilds = jsonArray_coilds.toJavaList(String.class);
            if (CollectionUtils.isEmpty(coilds)) {
                return ResultData.ResultDataFaultSelf(null, "出口卷号不能为空");
            }
            allProcessMapper.updateAbnormalReason2280_List(coilds,abnormalReason);
            return ResultData.ResultDataSuccessSelf("修改成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("修改失败,失败信息为" + e.getMessage(), null);
        }
    }

    /**
     * 将日期格式由YYYY-MM-DD HH:MM:SS 转为 YYYYMMDDHHSSMM
     * @param Date_str YYYY-MM-DD HH:MM:SS
     * @return YYYYMMDDHHSSMM
     */
    public String constructL3Date(String Date_str) {
        String l3Date = "";//时间格式：20250703075254
        try {
            String[] array_Time = Date_str.split("-");//时间格式：2025-06-01 00:00:01
                //构建时间格式：20250703075254
                String times2 = array_Time[2].replace(" ", "");
                times2 = times2.replace(":", "");
            l3Date = array_Time[0] + array_Time[1] + times2;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return l3Date;
    }


    @Override
    public void export1630(QueryDTO<TbYieldSearchCondition> queryDTO) {
        try {
            // 获取所有数据而不是分页数据
            TbYieldSearchCondition condition = queryDTO.getDto();
            LambdaQueryWrapper<TbYieldCal1630EntityExcel> wrapper = new LambdaQueryWrapper<>();

            String dbegin_str = constructL3Date(condition.getDbegin());
            String dend_str =constructL3Date(condition.getDend());

            if (condition != null) {
                wrapper.like(StringUtils.hasText(condition.getColdCoilId()), TbYieldCal1630EntityExcel::getCalCoilId, condition.getColdCoilId());
                wrapper.like(StringUtils.hasText(condition.getHotCoilId()), TbYieldCal1630EntityExcel::getColdCoilId, condition.getHotCoilId());
                wrapper.eq(StringUtils.hasText(condition.getPorCutFlag()), TbYieldCal1630EntityExcel::getPorCutheadFlag, condition.getPorCutFlag()).or().eq(StringUtils.hasText(condition.getPorCutFlag()), TbYieldCal1630EntityExcel::getPorCuttailFlag, condition.getPorCutFlag());
                wrapper.ge(StringUtils.hasText(condition.getDbegin()), TbYieldCal1630EntityExcel::getProdStartTime, dbegin_str);
                wrapper.le(StringUtils.hasText(condition.getDend()), TbYieldCal1630EntityExcel::getProdStartTime, dend_str);
            }

            // 查询符合条件的所有数据
            List<TbYieldCal1630EntityExcel> dataList = list(wrapper);

            // 设置导出参数
            ExportParams exportParams = new ExportParams("成材率1630表", "成材率1630表", ExcelType.XSSF);

            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TbYieldCal1630EntityExcel.class, dataList);

            // 行列固定
            if (workbook.getNumberOfSheets() > 0) {
                workbook.getSheetAt(0).createFreezePane(1, 2);
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("成材率1630表", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }




}
